package com.sczmgk.track.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.sczmgk.track.dialog.DialogFactory;


/**
 * Created by Administrator on 2017/6/12.
 */

public class PermissionUtils {

    public static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 1;
    public static final int REQUEST_PERMISSION_LOCATION = 2;
    public static final int REQUEST_PERMISSION_RECORD_AUDIO = 3;
    public static final int REQUEST_PERMISSION_CALL_PHONE = 4;
    public static final int REQUEST_PERMISSION_READ_PHONE_STATE = 5;
    public static final int REQUEST_PERMISSION_CAMERA = 6;
    public static final int REQUEST_PERMISSION_CONTACT = 7;
    public static final int REQUEST_PERMISSION_CAPTURE_AUDIO_OUTPUT = 8;
    public static final int REQUEST_LOCATION_SOURCE_SETTINGS = 9;
    private static final String TAG = PermissionUtils.class.getSimpleName();

    /**
     * 检查权限
     * @param context
     * @param permission  如： Manifest.permission.WRITE_EXTERNAL_STORAGE
     * @return  @return 返回true表示已打开权限或版本 <23
     */
    public static boolean checkPermission(Context context, String permission) {
        //检查权限

        if (Build.VERSION.SDK_INT >= 23) {

            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {

                return false;
            } else {
                return true;
            }

        } else {
            return true;
        }
    }

    /**
     * 检查定位功能是否已打开
     * @return   返回 true 表示打开
     */
    public static boolean checkLocationStatus(Activity activity) {

        LocationManager locationManager = (LocationManager) activity .getSystemService(Context.LOCATION_SERVICE);

        if(!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){

            MyLog.e(TAG,"没有打开GPS定位");

        }else{
            return true;
        }
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

            MyLog.e(TAG,"没有打开网络定位");
            return false;
        }else{
            return true;
        }
    }

    /**
     * 显示打开位置的对话框
     */
    public static  void showOpenLocationDialog(final Activity activity) {
        if(!CommonUtils.isAppOnForeground(activity)){
            return;
        }

        DialogFactory.chooseDialog(activity, "要使用定位功能,需要打开定位服务", "确定 ", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 转到手机设置界面，用户设置GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activity.startActivityForResult(intent, REQUEST_LOCATION_SOURCE_SETTINGS); // 设置完成后返回到原来的界面
            }
        });
    }
}
